package com.example.campsystem.tool;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.example.campsystem.config.AliyunOSSConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

@Component
@RequiredArgsConstructor
@ConfigurationProperties(prefix = "aliyun.oss")
public class OSSFileUtil {
    private final OSS ossClient;
    private final AliyunOSSConfig aliyunOSSConfig;
    private List<String> allowedContentTypes;

    public void setAllowedContentTypes(List<String> allowedContentTypes) {
        this.allowedContentTypes = allowedContentTypes;
    }

    public String uploadFile(MultipartFile file) {
        // 验证文件类型
        String contentType = file.getContentType();
        if (!allowedContentTypes.contains(contentType)) {
            throw new IllegalArgumentException("不支持的文件类型: " + contentType + 
                "。支持的类型: " + String.join(", ", allowedContentTypes));
        }

        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileName = "images/" + UUID.randomUUID().toString() + extension;
        
        try {
            InputStream inputStream = file.getInputStream();
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType(contentType);
            objectMetadata.setContentLength(file.getSize());
            
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                aliyunOSSConfig.getBucketName(), 
                fileName, 
                inputStream, 
                objectMetadata
            );
            
            ossClient.putObject(putObjectRequest);
            
            return aliyunOSSConfig.getUrlPrefix() + fileName;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage(), e);
        } catch (Exception e) {
            throw new RuntimeException("OSS服务异常: " + e.getMessage(), e);
        }
    }
}